package com.atguigu.gmall.common;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.model.GmallCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    //  发送消息的方法.
    public Boolean sendMsg(String exchange,String routingKey,Object obj){
        GmallCorrelationData gmallCorrelationData = new GmallCorrelationData();
        String uuid = UUID.randomUUID().toString();
        //  表示消息的唯一标识
        gmallCorrelationData.setId(uuid);
        gmallCorrelationData.setExchange(exchange);
        gmallCorrelationData.setRoutingKey(routingKey);
        gmallCorrelationData.setMessage(obj);

        //  将数据对象放入缓存.
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(gmallCorrelationData),10, TimeUnit.MINUTES);
        //  调用发送消息方法.
        //  rabbitTemplate.convertAndSend(exchange,routingKey,obj);
        //  将这个对象发送出去.
        rabbitTemplate.convertAndSend(exchange,routingKey,obj,gmallCorrelationData);
        //  默认返回true;
        return true;
    }

    //  发送延迟消息的方法.
    public Boolean sendDelayMsg(String exchange,String routingKey,Object obj,int delayTime){
        GmallCorrelationData gmallCorrelationData = new GmallCorrelationData();
        String uuid = UUID.randomUUID().toString();
        //  表示消息的唯一标识
        gmallCorrelationData.setId(uuid);
        gmallCorrelationData.setExchange(exchange);
        gmallCorrelationData.setRoutingKey(routingKey);
        gmallCorrelationData.setMessage(obj);
        //  设置好延迟时间.
        gmallCorrelationData.setDelayTime(delayTime);
        //  设置延迟消息.
        gmallCorrelationData.setDelay(true);

        //  将数据对象放入缓存.
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(gmallCorrelationData),10, TimeUnit.MINUTES);
        //  调用发送消息方法.
        //  rabbitTemplate.convertAndSend(exchange,routingKey,obj);
        //  将这个对象发送出去.
        this.rabbitTemplate.convertAndSend(exchange, routingKey, obj, message -> {
            //  设置延迟时间. 10 s ;
            message.getMessageProperties().setDelay(delayTime*1000);
            return message;
        },gmallCorrelationData);
        //  默认返回true;
        return true;
    }
}
